//
// Created by admin on 2022/2/8.
//

#include "AudioChannel.h"
#include "macro.h"
#include <cstring>
AudioChannel::AudioChannel() {

}
AudioChannel::~AudioChannel() {
    DELETE(buffer);
    if (audioCodec) {
        faacEncClose(audioCodec);
        audioCodec = 0;
    }
}

void AudioChannel::setAudioCallback(AudioCallback audioCallback) {
    this->audioCallback = audioCallback;
}

int AudioChannel::getInputSamples() {
    return inputSamples;
}

void AudioChannel::setAudioEncInfo(int samplesInHZ, int channels) {
    //打开编码器
    mChannels = channels;
    audioCodec = faacEncOpen(samplesInHZ,channels,&inputSamples,&maxOutputBytes);

    //设置编码器参数
    faacEncConfigurationPtr config =  faacEncGetCurrentConfiguration(audioCodec);
    config->mpegVersion = MPEG4;
    //lc 标准
    config->aacObjectType = LOW;
    //16位
    config->inputFormat = FAAC_INPUT_16BIT;
    // 编码出原始数据 既不是adts也不是adif
    config->outputFormat = 0;
    faacEncSetConfiguration(audioCodec, config);
    //设置输出缓冲区
    buffer = new u_char[maxOutputBytes];

}
//先解包
RTMPPacket* AudioChannel::getAudioTag() {
    u_char *buf;
    u_long len;
    faacEncGetDecoderSpecificInfo(audioCodec, &buf, &len);
    int bodySize = 2 + len;
    RTMPPacket *packet = new RTMPPacket;
    RTMPPacket_Alloc(packet, bodySize);
    //双声道
    packet->m_body[0] = 0xAF;
    if (mChannels == 1) {
        packet->m_body[0] = 0xAE;
    }
    packet->m_body[1] = 0x00;
    //图片数据
    memcpy(&packet->m_body[2], buf, len);

    packet->m_hasAbsTimestamp = 0;
    packet->m_nBodySize = bodySize;
    packet->m_packetType = RTMP_PACKET_TYPE_AUDIO;
    packet->m_nChannel = 0x11;
    packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
    return packet;

}
void AudioChannel::encodeData(int8_t *data) {
    int bytelen =  faacEncEncode(audioCodec, reinterpret_cast<int32_t *>(data), inputSamples, buffer, maxOutputBytes);
    //开始组包成rtmp 格式的数据
    if (bytelen > 0){
        int bodySize = 2 + bytelen;
        RTMPPacket *packet = new RTMPPacket;
        RTMPPacket_Alloc(packet,bodySize);
        //头拼接2个字节
        packet->m_body[0] = 0xAF;
        if (mChannels == 1){
            packet->m_body[0] = 0xAE;
        }
        //编码出的声音 都是 0x01
        packet->m_body[1] = 0x01;

        memcpy(&packet->m_body[2],buffer,bytelen);
        packet->m_hasAbsTimestamp = 0;
        packet->m_nBodySize = bodySize;
        packet->m_packetType = RTMP_PACKET_TYPE_AUDIO;
        packet->m_nChannel = 0x11;
        packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
        //数据的回调
        audioCallback(packet);

    }

}